#!/bin/bash
# OpenCloudOS 节点管理工具 - 基础设施启动脚本
# 仅启动 PostgreSQL 和 RabbitMQ 服务

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEPLOY_DIR="$(dirname "$SCRIPT_DIR")"

echo "🚀 启动OpenCloudOS节点管理工具基础设施"
echo "========================================"

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker未运行，请先启动Docker服务"
    echo "   sudo systemctl start docker"
    exit 1
fi

# 启动基础设施
echo "📦 启动基础设施服务..."
echo "  - PostgreSQL 数据库"
echo "  - RabbitMQ 消息队列"
echo ""

cd "$DEPLOY_DIR"
docker compose up -d

echo "⏳ 等待服务启动并进行健康检查..."

# 等待服务健康检查通过
max_attempts=30
attempt=0

while [ $attempt -lt $max_attempts ]; do
    if docker compose ps --filter "status=running" --filter "health=healthy" | grep -q "healthy"; then
        break
    fi
    attempt=$((attempt + 1))
    echo "   等待中... ($attempt/$max_attempts)"
    sleep 2
done

# 检查服务状态
echo ""
echo "📋 服务状态检查..."
docker compose ps

# 验证服务可用性
echo ""
echo "🔍 验证服务连接..."

# 检查PostgreSQL
if nc -z localhost 5432; then
    echo "✅ PostgreSQL (端口 5432) - 可访问"
else
    echo "❌ PostgreSQL (端口 5432) - 无法访问"
fi

# 检查RabbitMQ
if nc -z localhost 5672; then
    echo "✅ RabbitMQ (端口 5672) - 可访问"
else
    echo "❌ RabbitMQ (端口 5672) - 无法访问"
fi

if nc -z localhost 15672; then
    echo "✅ RabbitMQ 管理界面 (端口 15672) - 可访问"
else
    echo "❌ RabbitMQ 管理界面 (端口 15672) - 无法访问"
fi

echo ""
echo "🎉 基础设施启动完成！"
echo ""
echo "📋 连接信息:"
echo "  🐘 PostgreSQL:"
echo "     地址: localhost:5432"
echo "     数据库: node_management"
echo "     用户: admin / 密码: admin123"
echo ""
echo "  🐰 RabbitMQ:"
echo "     AMQP: localhost:5672"
echo "     用户: admin / 密码: admin123"
echo "     管理界面: http://localhost:15672"
echo ""
echo "💡 下一步:"
echo "  编译并启动应用程序:"
echo "    cargo build --release"
echo "    ./target/release/node_server start &"
echo "    ./target/release/node_agent --groups web,default &"
echo ""
echo "  或使用快速启动脚本:"
echo "    ./deploy/scripts/quick_start.sh"
    echo ""
    echo "🔧 启动应用程序:"
    echo "  Server: ./target/release/node_server start"
    echo "  Agent:  ./target/release/node_agent --groups web,default"
else
    echo "❌ 基础设施启动失败"
    docker compose -f "$(dirname "$0")/../docker-compose.yml" logs
    exit 1
fi
